package cn.unknownerror.ueteam.listener;

import cn.unknownerror.ueteam.team.ITeam;
import cn.unknownerror.ueteam.team.TeamAPI;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class PlayerChatListener implements Listener {
    public static Map<UUID, ArrayList<ITeam>> teamSelection= new HashMap<>();
    public static Map<UUID, Player> followLocation=new HashMap<>();
    @EventHandler
    public void playerJoinHandler(AsyncPlayerChatEvent e){
        ArrayList<ITeam> list = teamSelection.get(e.getPlayer().getUniqueId());
        if(list==null) return;
        int index;
        try {
            index=Integer.valueOf(e.getMessage());
        }catch (Exception ex){
            e.getPlayer().sendMessage("§c§l你输入了一个错误的编号。");
            teamSelection.remove(e.getPlayer().getUniqueId());
            e.setCancelled(true);
            return;
        }
        e.setCancelled(true);
        if(index>list.size()){
            e.getPlayer().sendMessage("§c§l你输入了一个错误的编号。");
            e.setCancelled(true);
            teamSelection.remove(e.getPlayer().getUniqueId());
            return;
        }
        ITeam team = list.get(index-1);
        if(TeamAPI.joinTeam(e.getPlayer().getUniqueId(),team.getUUID())) {
            e.getPlayer().sendMessage("§a§l您加入了队伍:" + team.getName());
            for(UUID member :TeamAPI.findTeamFromPlayer(e.getPlayer().getUniqueId()).getMembers()){
                Player m = Bukkit.getPlayer(member);
                if(m==null||!m.isOnline()) continue;
                if(m.getUniqueId().equals(e.getPlayer().getUniqueId())) continue;
                m.sendMessage("§a§l来自队伍的消息：§7§l新队员§f"+e.getPlayer().getName()+"§7§l加入队伍。");
            }
        }
        else e.getPlayer().sendMessage("§c§l§c§l加入失败，可能是队伍人数已满,或者队伍禁止加入。");
        teamSelection.remove(e.getPlayer().getUniqueId());
    }
    @EventHandler
    public void playerFollowHandler(AsyncPlayerChatEvent e){
        Player target=followLocation.get(e.getPlayer().getUniqueId());
        if(target==null||!target.isOnline()) return;
        if(e.getMessage().equals("follow"))e.setCancelled(true);
        if(e.getMessage().equals("follow")){
            e.getPlayer().teleport(target);
            followLocation.remove(e.getPlayer().getUniqueId());
        }
    }
}
